<script setup>
import { ref, watch, onUnmounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:modelValue'])

let isLoaded = false
const iframeRef = ref(null)

const onMessage = (e) => {
  const res = e.data
  if (res.cmd === 'change') {
    // 打印接收到的数据
    emit('update:modelValue', res.data)
  }
}

window.addEventListener('message', onMessage)

const onLoad = () => {
  iframeRef.value.contentWindow.postMessage({
    cmd: 'load',
    data: props.modelValue
  })
  if (props.modelValue) {
    isLoaded = true
  }
}

watch(
  () => props.modelValue,
  () => {
    if (!isLoaded && iframeRef.value?.contentWindow) {
      onLoad()
    }
  }
)

onUnmounted(() => {
  window.removeEventListener('message', onMessage)
})
</script>

<template>
  <div class="yaml-editor">
    <iframe ref="iframeRef" src="/yaml/index.html" @load="onLoad"></iframe>
  </div>
</template>

<style scoped lang="less">
.yaml-editor {
  width: 100%;
  height: 100%;

  iframe {
    width: 100%;
    height: 100%;
  }
  .grid-btn {
    margin-top: 5px;
    text-align: right;
  }
}
</style>
